import { defineStore } from 'pinia';
import { getCache, setCache } from '@/utils/cache';
import { USER_INFO_KEY } from '@/enums/cacheEnum';
import { getUserInfo } from '@/services/api';
import { useRequest } from 'alova';

interface UserState {
    userinfo: AnyObject;
}

const { send: sendGetUserInfo } = useRequest(getUserInfo, { immediate: false });

export const userStore = defineStore({
    id: 'user',
    state: (): UserState => ({
        userinfo: getCache<object>(USER_INFO_KEY),
    }),
    getters: {
        userInfo: (state) => state.userinfo,
        brokerStatus: (state) => state.userinfo.broker_status,
    },
    actions: {
        setUserInfo(userinfo: object) {
            setCache(USER_INFO_KEY, userinfo);
            this.userinfo = userinfo;
        },
        /**
         * @description 用户信息
         */
        async getUserinfo(): Promise<any> {
            try {
                const res: any = await sendGetUserInfo();
                this.setUserInfo(res);
                return Promise.resolve(res);
            } catch (err: any) {
                return Promise.reject(err);
            }
        },
    },
});
